﻿$(function () {
    var chat = $.connection.chat;

    var modalMessengerDialog = $("#dialogMessengerModal");

    $("#dialogMessengerModalLabel").find(".open").click(function () {
        openMessengerDialog();
        return false;
    });

    $("#dialogMessengerModal").find(".close").click(function () {
        closeMessengerDialog();
    });

    openMessengerDialog = function () {
        var browserName = navigator.appName;
        if (browserName == 'Microsoft Internet Explorer' && modalMessengerDialog.hasClass("fade")) {
            modalMessengerDialog.removeClass("fade");
        }
        modalMessengerDialog.modal({ show: true });
    };

    closeMessengerDialog = function () {
        modalMessengerDialog.modal('hide');
    };

    chat.client.send = function (message) {
        var dialogMessenger = $('#dialogMessengerModal');
        if (!dialogMessenger.hasClass('in')) {
            toastr.info(message);
        }
        //var messagesListTextArea = $('#messages-list');
        var messagesListTextArea = dialogMessenger.find("#messages-list");
        var newMessage = message.toString() + "\n";
        var messagesList = messagesListTextArea.val() + newMessage;
        messagesListTextArea.val(messagesList);

        messagesListTextArea.scrollTop(
        messagesListTextArea[0].scrollHeight - messagesListTextArea.height()
    );
    };

    chat.client.userEvent = function (message) {
        toastr.warning(message);
    };

    chat.client.updateUserList = function (message) {
        var userListTextArea = $('#user-list');
        var users = message.toString().replace(/\,/g, "\n");
        userListTextArea.val(users);
    };

    $.connection.hub.start().done(function () {
        $('#send').click(function () {
            var input = $('#msg');
            chat.server.send($('#msg').val());
            input.val('');
        });
    });
});